package com.szm.sentinelx.database.config;

import com.alibaba.cloud.sentinel.datasource.config.AbstractDataSourceProperties;
import org.springframework.util.ObjectUtils;

import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author: shaozeming
 * @date: 2022/8/13 14:56
 * @description: 所有的数据源配置类
 **/
public class SentinelXDataSourcePropertiesConfiguration {

    private SentinelXNacosDataSourceProperties nacos;

    public SentinelXNacosDataSourceProperties getNacos() {
        return nacos;
    }

    public void setNacos(SentinelXNacosDataSourceProperties nacos) {
        this.nacos = nacos;
    }

    public List<String> getValidField() {
        return Arrays.stream(this.getClass().getDeclaredFields()).map(field -> {
            try {
                if (!ObjectUtils.isEmpty(field.get(this))) {
                    return field.getName();
                }
                return null;
            }
            catch (IllegalAccessException e) {
                // won't happen
            }
            return null;
        }).filter(Objects::nonNull).collect(Collectors.toList());
    }


    public AbstractDataSourceProperties getValidDataSourceProperties() {
        List<String> invalidFields = getValidField();
        if (invalidFields.size() == 1) {
            try {
                this.getClass().getDeclaredField(invalidFields.get(0))
                        .setAccessible(true);
                return (AbstractDataSourceProperties) this.getClass()
                        .getDeclaredField(invalidFields.get(0)).get(this);
            }
            catch (IllegalAccessException e) {
                // won't happen
            }
            catch (NoSuchFieldException e) {
                // won't happen
            }
        }
        return null;
    }

}
